﻿using System.Web.UI.WebControls;

namespace Ficharts.Net
{
    #region 引用

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Text;
    using System.Web.UI;

    using Ficharts.Net.Enums;

    #endregion

    [DefaultProperty("Text")]
    [ToolboxData("<{0}:FiChart runat=server></{0}:FiChart>")]
    public class FiCharts : SingleSeriesChart
    {
        #region Fields

        private Dictionary<string, string> _SWFDictionary;

        #endregion

        #region Public Properties

        /// <summary>
        /// 图表样式类型,有白和黑两种,默认为白色
        /// </summary>
        public StyleMode ChartStyle { get; set; }

        /// <summary>
        /// 配置文件路径,存在此配置文件时，优先以配置文件显示
        /// </summary>
        public string ConfigFile { get; set; }

        /// <summary>
        /// 图表类型
        /// </summary>
        public ChartType ChartType { get; set; }

        

        [Bindable(true)]
        [DefaultValue("")]
        [Localizable(true)]
        public string XmlText
        {
            get
            {
                string s = (string)this.ViewState["XmlText"];
                return s ?? string.Empty;
            }

            set
            {
                this.ViewState["XmlText"] = value;
            }
        }

        

        #endregion

        #region Properties

        private Dictionary<string, string> SWFDictionary
        {
            get
            {
                if (this._SWFDictionary == null)
                {
                    this._SWFDictionary = new Dictionary<string, string>();
                    this._SWFDictionary.Add("Chart2D", this.getUrl("Chart2D.swf"));
                    this._SWFDictionary.Add("Pie2D", this.getUrl("Pie2D.swf"));
                }
                return this._SWFDictionary;
            }
        }

        #endregion

        #region Public Methods and Operators

        public new void DataBind()
        {
            this.XmlText = this.ToXml();
            this.JsonData = this.ToJson();
        }

        #endregion

        #region Methods

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            if (!this.Visible || !this.Enabled)
            {
                return;
            }

            //注册脚本
            if (!this.Page.ClientScript.IsClientScriptIncludeRegistered("_lib_fi_js"))
            {
                string jsFunctions = this.Page.ClientScript.GetWebResourceUrl(
                    typeof(FiCharts), "Ficharts.Net.Files.FiCharts.js");
                this.Page.ClientScript.RegisterClientScriptInclude("_lib_fi_js", jsFunctions);
            }

            //注册swf文件
            if (!this.Page.ClientScript.IsClientScriptIncludeRegistered("_lib_fi_res"))
            {
                this.Page.ClientScript.RegisterClientScriptBlock(
                    typeof(FiCharts), "_lib_get_res", this.GetJsFunctionForResources(), true);
            }
        }

        protected override void RenderContents(HtmlTextWriter output)
        {
            if (!this.Visible || !this.Enabled)
            {
                return;
            }
            string controlId = base.ClientID;
            string divId = "_fi_DIV_" + base.ClientID;
            string width = "'100%'";
            string height = "400";

            if (this.Width.Value > 0)
            {
                if (this.Width.Type == UnitType.Percentage)
                {
                    width = "'" + this.Width.Value + "%'";
                }
                else
                {
                    width = this.Width.Value.ToString();
                }
            }
            if (this.Height.Value > 0)
            {
                if (Height.Type == UnitType.Percentage)
                {
                    height = "'" + this.Height.Value + "%'";
                }
                else
                {
                    height = this.Height.Value.ToString();
                }
            }

            var oBuilder = new StringBuilder();

            oBuilder.AppendFormat(@"<div id='{0}'></div>", divId);
            oBuilder.AppendLine(@"<script type=""text/javascript"">");

            oBuilder.AppendFormat(@"var {0} = new Chart2D('{1}');", controlId, divId);
            oBuilder.AppendFormat("{0}.swfURL=_lib_gR('{1}');", controlId, this.ChartType);
            oBuilder.AppendLine(controlId + ".setSize(" + width + ", " + height + ");");

            if (this.ChartStyle == StyleMode.Black)
            {
                oBuilder.AppendLine(controlId + ".setStyle('Black');");
            }
            if (this.ChartStyle == StyleMode.Classic)
            {
                oBuilder.AppendLine(controlId + ".setStyle('Classic');");
            }
            if (this.ChartStyle == StyleMode.Simple)
            {
                oBuilder.AppendLine(controlId + ".setStyle('Simple');");
            }

            oBuilder.AppendFormat("{0}.setConfigXML('{1}');", controlId, this.XmlText);
            if (this.DataType == DataType.Json)
            {
                oBuilder.AppendFormat("{0}.setJsonData({1});", controlId, this.JsonData);
            }

            oBuilder.AppendFormat("{0}.render();", controlId);

            oBuilder.AppendLine(@"</script>");

            output.Write(oBuilder.ToString());
        }

        private string GetJsFunctionForResources()
        {
            StringBuilder oBuilder = new StringBuilder();

            oBuilder.AppendLine(@"_lib_gR = function(chart){");
            foreach (string key in this.SWFDictionary.Keys)
            {
                oBuilder.AppendLine(@"if(chart=='" + key + @"')");
                oBuilder.Append(@"{return '" + this.SWFDictionary[key] + @"';}");
            }
            oBuilder.AppendLine(@"}");

            return oBuilder.ToString();
        }

        private string getUrl(string swf)
        {
            return this.Page.ClientScript.GetWebResourceUrl(typeof(FiCharts), "Ficharts.Net.Files." + swf);
        }

        #endregion
    }
}